import React, { Fragment, useState, useEffect } from 'react'

import { PageHeaderWrapper } from '@ant-design/pro-layout'
import {
    Card,
    Row,
    Col,
    Button,
    Table,
    Divider,
    Pagination,
    Modal,
    Form,
    Input,
    Popconfirm,
    message,
    Select,
    Radio, Switch
} from 'antd'

const { Option } = Select

import {
  getChannelList,
  addChannel,
  delChannelById,
  isRepeatCode, editChannel,
    updateChannelConfigState,
    updateChannelPath
} from '@/services/channel'
import channelStyles from './index.less'
import config from './config'
import moment from "moment/moment";
import goodsService from "@/services/goods";
import CopyToClipboard from '@/components/CopyToClipboard';
const ChannelList = props => {
  const { getFieldDecorator } = props.form

  const [pageInfo, setPageInfo] = useState({ pageNumber: 1, pageSize: 10 })
  const [visible, setVisible] = useState(false)
  const [channelList, setChannelList] = useState([])
  const [total, setTotal] = useState(0)
  const [detail, setDetail] = useState({})
  const [subordinateFlag, setSubordinateFlag] = useState(false)//是否开通渠道权限
  const [channelCode, setChannelCode] = useState('')
    const [channelName, setChannelName] = useState('')
  const loadList = async () => {
    try {
      const {
        data: { records, total: allTotal }
      } = await getChannelList(pageInfo)
      setChannelList(records)
      setTotal(allTotal)
    } catch (error) {
      message.error(error.message)
    }
  }

  const onCopyChannelUrl = async record => {
    try {
      const baseUrl = 'https://ds.alipay.com/?scheme='
      await navigator.clipboard.writeText(
        baseUrl +
          encodeURIComponent(record.channelUrl.split('scheme')[1].slice(1))
      )
      message.success('复制链接成功')
    } catch (error) {
      message.error('您的浏览器不支持复制功能')
    }
  }

  const confirm = async id => {
    try {
      await delChannelById(id)
      message.success('删除成功')
      loadList()
    } catch (error) {
      message.warn(error.message)
    }
  }

  const cancel = () => {
    message.warn('您取消了删除动作')
  }
  const edit =  (record) => {
    setSubordinateFlag(record.subordinateFlag)
    setVisible(true)
    setDetail({...record})
  }
  const add =  (record) => {
    setSubordinateFlag(false)
    setVisible(true)
    setDetail({})
  }
  //更新渠道链接
    const updateChannel = async record => {
        await  updateChannelPath({
            id: record.id,
        })
            .then(res => {
                message.success('渠道链接更新成功')
                loadList()
            })
    }
    //渠道启用禁用
    const handleHide = async record => {
        await  updateChannelConfigState({
            id: record.id,
            pmState: record.pmState === 1 ? 0 : 1
        })
            .then(res => {
                message.success('修改成功')
                loadList()
            })
    }
  const onSearchBtn =()=>{
      setPageInfo({ ...pageInfo, pageNumber: 1, pageSize: 10 ,channelCode,channelName})
  }
    const onReset =()=>{
        setPageInfo({
            pageNumber: 1,
            pageSize: 10,
        })
        setChannelCode('')
        setChannelName('')
    }
  const columns = [
    {
      title: '渠道名称',
      dataIndex: 'channelName',
      align: 'center'
    },
    {
      title: '联系人',
      dataIndex: 'contacts',
      align: 'center'
    },
    {
      title: '账户手机号',
      dataIndex: 'phone',
      align: 'center'
    },
    {
      title: '推广链接',
      dataIndex: 'channelCode',
      align: 'center'
    },
    {
      title: '渠道保护期（天）',
      dataIndex: 'expireDay',
      align: 'center'
    },
    {
      title: '添加日期',
      dataIndex: 'createTime',
      align: 'center'
    },
      {
          title: '渠道链接',
          dataIndex: 'channelPath',
          width: '320px',
          align: 'center',
          render:(text, record) =>{
              return (
                  <>
                      {
                        <CopyToClipboard text={` https://ds.alipay.com/?scheme=${encodeURIComponent(record.channelUrl.split('scheme')[1].slice(1))}`} />
                      }
                  </>
              )
          }
      },
      {
          title: '渠道启用/禁用',
          dataIndex: 'pmState',
          align: 'center',
          render: (text, record) => {
              return (
                  <>
                      <span>{text ? '启用' : '禁用'}</span>
                      &nbsp;
                      <Switch
                          checked={text}
                          onChange={() => handleHide(record)}
                      />
                  </>
              )
          }
      },
    {
      title: '操作',
      dataIndex: 'name4',
      align: 'center',
      render: (text, record) => (
        <span>
          <Button
            type="link"
            size="small"
            onClick={() => onCopyChannelUrl(record)}
          >
            复制
          </Button>

          <Divider type="vertical" />
          <Popconfirm
            title="您确定要删除该渠道吗？"
            cancelText="取消"
            okText="确定"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
          >
            <Button type="link" size="small">
              删除
            </Button>
          </Popconfirm>
              <Divider type="vertical" />
              <Button type="link" size="small" onClick={() => edit(record)}>
              修改
            </Button>
             {/* <Button type="link" size="small" onClick={() => updateChannel(record)}>
              更新渠道链接
            </Button> */}
        </span>
      )
    }
  ]

  const resetFields = () => {
    props.form.resetFields()
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 10 },
      sm: { span: 6 }
    },
    wrapperCol: {
      xs: { span: 10 },
      sm: { span: 16 }
    }
  }

  const onSubmit = e => {
    e.preventDefault()
    props.form.validateFields(async (err, values) => {
      if (!err) {
        const baseAliPayUrl =
          'https://ds.alipay.com/?scheme=alipays://platformapi/startapp'
        const channelUrl = `${baseAliPayUrl}?appId=${config.appId}&page=pages/home/index&query=thirdplatform=${values.channelCode}`
        const params = values || {};
        for (const key in params) {
          if (typeof params[key] === 'string') {
            params[key] = params[key].trim();
          }
        }
       detail.id ? await editChannel({ ...params, id:detail.id,uid:detail.uid,channelUrl }) : await addChannel({ ...params, channelUrl })
        resetFields()
        detail.id ? message.success('修改渠道成功') : message.success('添加渠道成功')
        setVisible(false)
        loadList()

      }
    })
  }

  const validCheckCode = async (rule, value, callback) => {
    try {
      if (!value) return message.warning('请输入渠道编号')
      const { data: isRepeat } = await isRepeatCode(value)
      if (isRepeat && ! detail.id) {
        callback('渠道编号已存在，请重新输入')
      } else {
        callback()
      }
    } catch (error) {
      callback(error.message)
    }
    return ''
  }

  const handleOk = () => {
    setVisible(false)
  }

  const handleCancel = () => {
    resetFields()
    setVisible(false)
    setSubordinateFlag(false)
  }

  useEffect(() => {
    loadList()
  }, [pageInfo])

  const onPageChange = pageNumber => {
    setPageInfo({ ...pageInfo, pageNumber })
  }

  const onSizeChange = (current, pageSize) => {
    setPageInfo({ ...pageInfo, pageSize })
  }

  return (
    <Fragment>
      <PageHeaderWrapper title="渠道管理">
        <Card>
            <Row gutter={16}>
                <Col span={24}>
                    <Row type="flex">
                        <Col span={12}>
                            <Row type="flex">
                                <Col span={12}>
                                   渠道编号：
                                    <Input
                                        placeholder="请输入渠道编号"
                                        style={{ width: 150 }}
                                        value={channelCode}
                                        onChange={e => setChannelCode(e.target.value)}
                                    />
                                </Col>
                                <Col span={12}>
                                    渠道名称：
                                    <Input
                                        placeholder="请输入渠道名称"
                                        style={{ width: 150 }}
                                        value={channelName}
                                      onChange={e => setChannelName(e.target.value)}
                                    />
                                </Col>
                            </Row>
                        </Col>
                        <Col span={12}>
                            <Row type="flex" justify="end">
                                <Button type="primary" onClick={onSearchBtn}>
                                    查询
                                </Button>
                                <Button type="info" onClick={onReset}>
                                    重置
                                </Button>
                                <Button type="primary" onClick={() => add()}>
                                    新增渠道
                                </Button>
                            </Row>
                        </Col>
                    </Row>
                </Col>
            </Row>
          <Table
            style={{ marginTop: 20 }}
            bordered
            dataSource={channelList}
            columns={columns}
            pagination={false}
            rowKey="id"
          />

          <Pagination
            style={{ marginTop: 20, textAlign: 'right' }}
            showTotal={() => `共有 ${total} 条`}
            total={total}
            current={pageInfo.pageNumber}
            pageSize={pageInfo.pageSize}
            defaultPageSize={5}
            pageSizeOptions={['5', '10', '15', '20']}
            showSizeChanger
            showQuickJumper
            onChange={onPageChange}
            onShowSizeChange={onSizeChange}
          />
        </Card>
      </PageHeaderWrapper>

      <Modal
        title={detail.id ?"修改渠道" :"新增渠道"}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <Form {...formItemLayout} onSubmit={onSubmit}>
          <Form.Item label="渠道名称：" hasFeedback>
            {getFieldDecorator('channelName', {
              rules: [{ required: true,
                message: '请输入渠道名称！' ,max:15 , pattern: /^[^\s]*$/,
              }],
              initialValue: detail.channelName || '',
            })(<Input placeholder="请输入渠道名称" />)}
          </Form.Item>
          <Form.Item label="渠道代码：" hasFeedback>
            {getFieldDecorator('channelCode', {
              rules: [
                { required: true, message: '请输入渠道代码',pattern: /^[^\s]*$/, },
                {
                  validator: validCheckCode,
                  message: '渠道编号已存在，请重新输入',
                  max:15,

                }
              ],
              initialValue: detail.channelCode || '',
              validateTrigger: 'onBlur'
            })(<Input placeholder="请输入渠道代码" disabled={detail.id} />)}
          </Form.Item>
          <Form.Item label="联系人：" hasFeedback>
            {getFieldDecorator('contacts', {
              rules: [{ required: true, message: '请输入联系人',max:15 , pattern: /^[^\s]*$/,}],
              initialValue: detail.contacts || '',
            })(<Input placeholder="请输入联系人" />)}
          </Form.Item>
          <Form.Item label="账户手机号：" hasFeedback>
            {getFieldDecorator('phone', {
              rules: [
                { required: true, message: '请输入账户手机号' },
                { max: 11, message: '手机号长度有误' },
                {
                  pattern: /1[3-9]\d{9}/,
                  message: '手机号格式不正确'
                }
              ],
              initialValue: detail.phone || '',
            })(<Input placeholder="请输入账户手机号" />)}
          </Form.Item>
          <Form.Item label="账户密码：" hasFeedback>
            {getFieldDecorator('pwd', {
              rules: [{ required: true, message: '请输入密码',max:15, pattern: /^[^\s]*$/, }],
              initialValue: detail.pwd || '',
            })(<Input placeholder="请输入密码" />)}
          </Form.Item>

          {/* 新加结算方式，结算价格，保护期，是否开通渠道权限 */}
          <Form.Item label="结算方式" hasFeedback>
            {getFieldDecorator('priceType', {
              rules: [{ required: true, message: '请选择结算方式' }],
              initialValue: JSON.stringify(detail.priceType),
            })(
              <Select placeholder="请选择结算方式">
                <Option value="2">UV（按点击结算）</Option>
                <Option value="3">CPS（按成交结算）</Option>
                <Option value="1">CPA（按注册结算）</Option>
              </Select>
            )}
          </Form.Item>
          <Form.Item label="结算价格" hasFeedback>
            {getFieldDecorator('price', {
              // 只能输入数字
              rules: [
                { required: true, message: '请输入结算价格' },
                {
                  pattern: /^[0-9]+(\.[0-9]+)?$/,
                  message: '只能输入数字或小数'
                }
              ],
              initialValue: detail.price || '',
            })(<Input placeholder="请输入结算价格" suffix="元" />)}
          </Form.Item>
          {/* 1 3 7 14 永久 */}
          <Form.Item label="渠道保护期" hasFeedback>
            {getFieldDecorator('expireDay', {
              rules: [
                { required: true, message: '请输入渠道保护期' },
                {
                  pattern: /^\d+$/,
                  message: '只能输入数字'
                }
              ],
              initialValue: detail.expireDay || '',
            })(<Input placeholder="请输入渠道保护期" suffix="天" />)}
          </Form.Item>
          <Form.Item label="开通渠道权限">
            {getFieldDecorator('subordinateFlag', {
              rules: [{ required: true, message: '请选择是否开通渠道权限' }],
              initialValue: subordinateFlag ,
            })(
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            )}
          </Form.Item>

          {/* 操作按钮区域 */}
          <Row type="flex" justify="center">
            <Button type="info" onClick={handleCancel}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Row>
        </Form>
      </Modal>
    </Fragment>
  )
}

const WrapperChannelList = Form.create({ name: 'channel-list' })(ChannelList)

export default WrapperChannelList
